<script setup lang="ts">
import { ref, reactive, nextTick } from "vue"
import type { Page } from "@/api/types/page"
import type { Dishes, DishesSearchParam } from "@/api/dishes/types"
import { getDishesList, addDishes, deleteDishes, updateDishes } from "@/api/dishes";
import { listByType } from "@/api/ingredients"
import { ElMessage, ElMessageBox, type FormRules, type UploadFile, type UploadProps } from "element-plus";
import { tr } from "element-plus/es/locales.mjs";
import type { Ingredients } from "@/api/ingredients/types";

const pageNum = ref(1)
const pageSize = ref(1)
const total = ref(1)

const dishesList = ref<Dishes[]>([])
const queryFormRef = ref();
const queryForm = ref<DishesSearchParam>({
    name: '',



})
const base_url = import.meta.env.VITE_APP_BASE_API
const listDishes = (pageNumber = 1) => {
    pageNum.value = pageNumber
    getDishesList(pageNum.value, pageSize.value, queryForm.value)
        .then((page: Page<Dishes>) => {
            total.value = page.total
            dishesList.value = page.rows

        }).catch(e => {
            console.log(e)
        })
}
const resetQueryForm = () => {
    queryFormRef.value.resetFields()
    listDishes()
}
listDishes()

const dishesFormRef = ref()
const dishesForm = ref<Dishes>({
    name: '',
    url: '',
    main: '',
    mainNum: 10,
    minor: '',
    minorNum: 10,
    seasoning: '',
    seasoningNum: 10,
    description: ''

})
const dishesFormRules = ref<FormRules>({
    name: [{ required: true, message: '请输入菜品名称' }],
    url: [{ required: true, message: '请上传图片' }],
    main: [{ required: true, message: '请选择主要食材' }],
    mainNum: [{ required: true, message: '请输入数量' }],
    minor: [{ required: true, message: '请选择辅助食材' }],
    minorNum: [{ required: true, message: '请选择数量' }],
    seasoning: [{ required: true, message: '请输入配料' }],
    seasoningNum: [{ required: true, message: '请输入配料数量' }],
    description: [{ required: true, message: '请输入描述信息' }]

})
const dishesFormVisible = ref(false)
const fileList = ref<UploadFile[]>([])
const fileLimit = ref(1)
const dishesFormTitile = ref('添加菜品')
const handleOnSuccess: UploadProps['onSuccess'] = (r, f, fs) => {
    dishesForm.value.url = r.data
    dishesFormRef.value.validateFiled('url')

}


const handleBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const isJPG = rawFile.type == 'image/jpeg'
    const isPNG = rawFile.type == 'image/png'
    console.log(rawFile.type)
    const isLt1MB = rawFile.size / 1024 / 1024 < 1
    if (!isJPG && !isPNG) {
        ElMessage.warning('仅支持png/jpg格式')
        return false
    }
    if (!isLt1MB) {
        ElMessage.warning('文件大小不能超过1mb')
        return false
    }

}
const handleOnExcceed: UploadProps['onExceed'] = (files) => {
    ElMessage.warning(
        '不能超过一张图片'
    )

}
const handleOnRemove: UploadProps['onRemove'] = (f, fs) => {
    dishesForm.value.url = ''
    fileList.value = []
    dishesFormRef.value.validateFiled('url')
}
const handleAdd = () => {
    dishesFormVisible.value = true
    nextTick(() => {
        dishesFormTitile.value = '添加菜品'
        dishesForm.value = {
            name: '',
            url: '',
            main: '',
            mainNum: 10,
            minor: '',
            minorNum: 10,
            seasoning: '',
            seasoningNum: 10,
            description: ''

        }
        fileList.value = []
        dishesFormRef.value.resetFields()
    })

}
const handleUpdate = (row:any) => {
    dishesFormVisible.value = true

nextTick(() => {
    dishesFormTitile.value = '修改'
    dishesForm.value = { ...row }
    fileList.value = [{ name: row.url, url: base_url + row.url }]
})
}

const mainList = ref<Ingredients[]>([])
const minorList = ref<Ingredients[]>([])
const seasoningList = ref<Ingredients[]>([])

const getIngredientsTypeList = async()=>{
    try{
    mainList.value = await listByType('1')
    minorList.value = await listByType('2')
    seasoningList.value = await listByType('3')
    }catch(e){
        console.log(e)
    }
}
getIngredientsTypeList()
const confirm = ()=>{
    dishesFormRef.value.validate(async (valid:boolean)=>{
        if(valid){
            if(!dishesForm.value.id){
                await addDishes(dishesForm.value)
                pageNum.value=1
            }else{
                await updateDishes(dishesForm.value)
            }
            ElMessage.success('操作成功')
            dishesFormVisible.value = false
            listDishes(pageNum.value)
            
        }

    })
}

/* 点击删除 */
const handleDelete = (id:number) => {
    ElMessageBox.confirm(
        '确定要删除食材吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        await deleteDishes(id)
        ElMessage({
            type: 'success',
            message: '删除成功!',
        })
        listDishes(pageNum.value)
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '删除取消!',
        })
    })
}
</script>

<template>
    <div class="app-container">
        <el-form inline ref="queryFormRef" :model="queryForm" @submit.native.prevent>
            <el-form-item label="菜品名称" prop="name">
                <el-input v-model="queryForm.name" placeholder="请输入菜品名称" @keyup.enter.native="listDishes()"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" plain @click="listDishes()">搜索</el-button>
                <el-button type="info" icon="Refresh" plain @click="resetQueryForm">重置</el-button>
                <el-button type="success" icon="Plus" @click="handleAdd">添加</el-button>
            </el-form-item>
        </el-form>
        <!--列表 -->
        <el-table border stripe :data="dishesList" style="width: 100%;">
            <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
            <el-table-column prop="name" label="菜品名称" align="center"></el-table-column>

            <el-table-column prop="mainName" label="主要食材" align="center"></el-table-column>
            <el-table-column prop="minorName" label="辅助食材" align="center"></el-table-column>
            <el-table-column prop="seasoningName" label="配料" align="center"></el-table-column>
            <el-table-column label="图片" align="center">
                <template #default="scope">
                    <el-image :src="base_url + scope.row.url" style="width: 40px; height: 40px;"
                        :preview-src-list="[base_url + scope.row.url]"></el-image>
                </template>

            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" plain icon="Edit" circle @click="handleUpdate(scope.row)"></el-button>
                    <el-button type="danger" @click="handleDelete(scope.row.id)" icon="Delete" circle></el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination style="margin-top:10px ;" :total="total" layout="total,sizes,prev,pager,next,jumper" background
            :page-sizes="[1, 5, 10, 50]"
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            @current-change="listDishes" 
            @size-change="listDishes()">
        </el-pagination>
    </div>

    <el-dialog v-model="dishesFormVisible" :title="dishesFormTitile" width="600" close-on-click-modal="false">
        <el-form :model="dishesForm" ref="dishesFormRef" :rules="dishesFormRules" label-width="80">
            <el-form-item label="菜品名称" prop="name">
                <el-input v-model="dishesForm.name" placeholder="请输入菜品名称" />
            </el-form-item>
            <el-form-item label="菜品图片" prop="url">
                <el-upload v-model:file-list="fileList" class="upload-demo"
                    :action="base_url + '/dishes-service/upload/image'" :on-success="handleOnSuccess"
                    :on-exceed="handleOnExcceed" :before-upload="handleBeforeUpload" :on-remove="handleOnRemove"
                    :limit="fileLimit" list-type="picture">
                    <el-button type="primary">点击上传</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            仅支持pngjpg格式 大小不超过1M
                        </div>
                    </template>
                </el-upload>

            </el-form-item>
            <div style="display: flex;">
                <el-form-item prop="main" label="主要食材">
                <el-select v-model="dishesForm.main" clearable placeholder="请选择主要食材" style="width: 180px;">
                    <el-option v-for="item in mainList"
                        
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="mainNum" label="分量">

                <el-input-number v-model="dishesForm.mainNum" :step="1"></el-input-number>
            </el-form-item>

            </div>
        
            <div style="display: flex;">
                <el-form-item prop="minor" label="辅助食材">
                <el-select v-model="dishesForm.minor" clearable placeholder="请选择主要食材" style="width: 180px;">
                    <el-option v-for="item in minorList"
                        
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="minorNum" label="分量">

                <el-input-number v-model="dishesForm.minorNum" :step="1"></el-input-number>
            </el-form-item>

            </div>
            <div style="display: flex;">
                <el-form-item prop="seasoning" label="调料">
                <el-select v-model="dishesForm.seasoning" clearable placeholder="请选择主要食材" style="width: 180px;">
                    <el-option v-for="item in seasoningList"
                        
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="seasoningNum" label="分量">

                <el-input-number v-model="dishesForm.seasoningNum" :step="1"></el-input-number>
            </el-form-item>

            </div>
            <el-form-item prop="description" label="食品描述">
                <el-input  type="textarea" v-model="dishesForm.description" placeholder="请输入菜品名称" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dishesFormVisible = false">取消</el-button>
                <el-button type="primary" @click="confirm">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<style scoped>
.el-upload-list__item {
    transition: none !important;
    -webkit-transition: nonne !important;
}

.el-upload-list__item-name {
    transition: none !important;
    -webkit-transition: nonne !important;
}</style>